/*
 * This file is part of BestApp.

    BestApp is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BestApp is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BestApp.  If not, see <http://www.gnu.org/licenses/>.

 */

package org.enate.BESTApp;

import mobi.intuitit.android.content.LauncherIntent;
import mobi.intuitit.android.widget.BoundRemoteViews;
import mobi.intuitit.android.widget.SimpleRemoteViews;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.Toast;

public class AppWidget4x4 extends AppWidgetProvider {
	//-------------------------------------------------------------------------------------------------------
	// ~~~ Variables ~~~
	private static final String TAG = "AppWidget4x4";
	private static final boolean LOLCAT = true;
	
	static int[] allAppWidgets = null;
	
	//-------------------------------------------------------------------------------------------------------
	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {this.onDeleted(context, new int[] { appWidgetId });}
		} 
		else if (TextUtils.equals(action, LauncherIntent.Action.ACTION_READY)||TextUtils.equals(action, "android.provider.Telephony.SMS_RECEIVED")) {
			onAppWidgetReady(context, intent);
		}
		 
		else if (TextUtils.equals(action, LauncherIntent.Action.ACTION_ITEM_CLICK)){onItemClick(context,intent);} 
		else if (TextUtils.equals(action, LauncherIntent.Action.ACTION_VIEW_CLICK)){onClick(context,intent,-1);} 
		
		else if (TextUtils.equals(action, ACTION_CONTACT_PHOTO_CLICK)){onClick(context,intent,R.id.contact_photo);}
		else if (TextUtils.equals(action, ACTION_CONTACT_NAME_CLICK)){onClick(context,intent,R.id.txt_person_name);}
		else if (TextUtils.equals(action, ACTION_SMS_MESSAGE_BODY_TEXT_CLICK)){onClick(context, intent, R.id.txt_person_body);}
		else if (TextUtils.equals(action, API.ACTION_CONTACT_PHOTO_CLICK)){onClick(context,intent,R.id.contact_photo);}
		else if (TextUtils.equals(action, API.ACTION_CONTACT_NAME_CLICK)){onClick(context,intent,R.id.txt_person_name);}
		else if (TextUtils.equals(action, API.ACTION_SMS_MESSAGE_BODY_TEXT_CLICK)){onClick(context,intent,R.id.txt_person_body);}
		else if (TextUtils.equals(action, LauncherIntent.Error.ERROR_SCROLL_CURSOR)){}
		else if (TextUtils.equals(action, LauncherIntent.Action.ACTION_FINISH)){}
		else {super.onReceive(context, intent);}
	}
	
	//-------------------------------------------------------------------------------------------------------	
	private void onClick(Context ctx, Intent intent, int viewID){
		final String str_viewClickMessage = intent.getStringExtra("viewMessage");
		Intent launch = new Intent(Intent.ACTION_VIEW);
		switch (viewID){
		case R.id.contact_photo:
			if(str_viewClickMessage.equals("NAN")){Toast.makeText(ctx, "Contact not found :C", Toast.LENGTH_SHORT);}
			else{
				launch = new Intent(Intent.ACTION_VIEW)
				.setData(Uri.parse(ContactsContract.Contacts.CONTENT_LOOKUP_URI + "/" + str_viewClickMessage));
				launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				launch.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
				launch.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
				launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				launch.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
				launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				try {ctx.startActivity(launch);}
				catch(Exception e){Toast.makeText(ctx,"Error viewing contact ["+str_viewClickMessage+"]", Toast.LENGTH_SHORT);}
			}
			break;
		case R.id.txt_person_name:
		case R.id.txt_person_body:
		case R.id.txt_datestamp:
		case R.id.widget_element_rl:		
			// Will replace this by updating the widget with the thread view
			launch.setData(Uri.parse("content://mms-sms/conversations/"+str_viewClickMessage)); 
			launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			launch.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
			launch.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
			launch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			launch.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			try {ctx.startActivity(launch);}
			catch(Exception e){Toast.makeText(ctx,"Error viewing thread D:", Toast.LENGTH_SHORT);}
			break;
		}
	}	
	private void onItemClick(Context context, Intent intent) {}
	

	//-------------------------------------------------------------------------------------------------------
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		if (appWidgetIds == null) {appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, AppWidget4x4.class));}
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_core);
        views.setOnClickPendingIntent(R.id.sms_compose, intentConstructor(context, INTENT_COMPOSE_SMS, "", -1));
        views.setOnClickPendingIntent(R.id.refresh_button, intentConstructor(context, INTENT_VIEWCONVERSATIONS_SMS, "", -1));
        views.setTextViewText(R.id.sms_unread, API.getUnreadSmsCount(context, 0)+"");
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {appWidgetManager.updateAppWidget(appWidgetIds[i], views);}
	}

	//-------------------------------------------------------------------------------------------------------
	@Override
	public void onDeleted(Context ctx, int[] appWidgetIds) {
        allAppWidgets = DataProvider.getAllWidgetIds(ctx);
        final int allAppWidgetsN = appWidgetIds.length;
        final int appWidgetIdsN = appWidgetIds.length;
		if(allAppWidgetsN-appWidgetIdsN<1){DataProvider.unregisterSMSObserver();}
	}
	
	//-------------------------------------------------------------------------------------------------------
	public static void onAppWidgetReady(Context context, Intent intent) {
		if (null==intent){return;}
		int APIVersion = intent.getExtras().getInt(LauncherIntent.Extra.EXTRA_API_VERSION, 1);
		int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
		if (0>appWidgetId) {return;}
		if (2>APIVersion) {
			RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_core);
			AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, views);
			return;
		}context.sendBroadcast(CreateMakeScrollableIntent(context, appWidgetId)); 
	}
	
	//-------------------------------------------------------------------------------------------------------
	public static Intent CreateMakeScrollableIntent(Context context, int appWidgetId) {
		String uri_ViewWidget = DataProvider.CONTENT_URI_MESSAGES.buildUpon().appendEncodedPath(Integer.toString(appWidgetId)).toString();
		Intent result = new Intent(LauncherIntent.Action.ACTION_SCROLL_WIDGET_START);
		result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		result.putExtra(LauncherIntent.Extra.EXTRA_VIEW_ID, R.id.widget_list_msgs_layout);
		result.putExtra(LauncherIntent.Extra.Scroll.EXTRA_DATA_PROVIDER_ALLOW_REQUERY, true);
		SimpleRemoteViews mViews = new SimpleRemoteViews(R.layout.widget_dummy_listview);
		result.putExtra(LauncherIntent.Extra.Scroll.EXTRA_LISTVIEW_REMOTEVIEWS, mViews);
		
		int itemresid = R.layout.widget_list_element;
		BoundRemoteViews itemViews = new BoundRemoteViews(itemresid);

		itemViews.setBoundCharSequence(R.id.txt_person_name, "setText", API.DataProviderColumns_CONVERSATIONLIST.contact_name.ordinal(),0);
		itemViews.setBoundCharSequence(R.id.txt_person_body, "setText", API.DataProviderColumns_CONVERSATIONLIST.snippet.ordinal(),0);
		itemViews.setBoundCharSequence(R.id.txt_datestamp, "setText",   API.DataProviderColumns_CONVERSATIONLIST.date.ordinal(),0);
		itemViews.setBoundBitmap(R.id.contact_photo, "setImageBitmap",  API.DataProviderColumns_CONVERSATIONLIST.contact_photo.ordinal(), R.drawable.avatar1); //

		Intent intent = new Intent(context, AppWidget4x4.class);
		intent.setAction(API.ACTION_CONTACT_PHOTO_CLICK);
		intent.setData(Uri.parse(uri_ViewWidget));
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);		
		PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		itemViews.SetBoundOnClickIntent(R.id.contact_photo,pi,"viewMessage",API.DataProviderColumns_CONVERSATIONLIST.lookup_id.ordinal());

		intent = new Intent(context, AppWidget4x4.class);
		intent.setAction(API.ACTION_CONTACT_NAME_CLICK);
		intent.setData(Uri.parse(uri_ViewWidget));
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);		
		pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		itemViews.SetBoundOnClickIntent(R.id.txt_person_name,pi,"viewMessage",API.DataProviderColumns_CONVERSATIONLIST._id.ordinal());

		intent = new Intent(context, AppWidget4x4.class);
		intent.setAction(API.ACTION_SMS_MESSAGE_BODY_TEXT_CLICK);
		intent.setData(Uri.parse(uri_ViewWidget));
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);		
		pi = PendingIntent.getBroadcast(context, 0, intent, 0);
		itemViews.SetBoundOnClickIntent(R.id.txt_person_body,pi,"viewMessage",API.DataProviderColumns_CONVERSATIONLIST._id.ordinal());

		result.putExtra(LauncherIntent.Extra.Scroll.EXTRA_ITEM_LAYOUT_REMOTEVIEWS, itemViews);
		putProvider(result, uri_ViewWidget);
		result.putExtra(LauncherIntent.Extra.Scroll.EXTRA_ITEM_CHILDREN_CLICKABLE, true);
		API.processWidgetUpdate(context);
		return result;
	}
	
	//-------------------------------------------------------------------------------------------------------
	protected static void putProvider(Intent intent, String widgetUri) {
		String whereClause = null;
		String orderBy = null;
		String[] selectionArgs = null;
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_DATA_URI, widgetUri);
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_PROJECTION, API.PROJECTION_APPWIDGETS_CONVERSATIONLIST);
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_SELECTION, whereClause);
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_SELECTION_ARGUMENTS, selectionArgs);
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_SORT_ORDER, orderBy);
		intent.putExtra(LauncherIntent.Extra.Scroll.EXTRA_ITEM_CHILDREN_CLICKABLE, true);
	}
	
	public static final int INTENT_COMPOSE_SMS = 0;
	public static final int INTENT_VIEWCONVERSATIONS_SMS = 1;

	public static final int INTENT_ACTION_CONTACT_PHOTO_CLICK = 2;
	public static final int INTENT_ACTION_CONTACT_NAME_CLICK = 3;
	public static final int INTENT_ACTION_SMS_MESSAGE_BODY_TEXT_CLICK = 4;
	
	// There's no way to get the click view's ID so:
	public static final String ACTION_CONTACT_PHOTO_CLICK = "Scrolly.ACTION_CONTACT_PHOTO_CLICK";
	public static final String ACTION_CONTACT_NAME_CLICK = "Scrolly.API.ACTION_CONTACT_NAME_CLICK";
	public static final String ACTION_SMS_MESSAGE_BODY_TEXT_CLICK = "Scrolly.ACTION_SMS_MESSAGE_BODY_TEXT_CLICK";

	public static Intent intent_intentConstructor;	
	public static PendingIntent intentConstructor(Context ctx, int intentType, String uri_ViewWidget, int appWidgetId) {
		switch(intentType) {
		case INTENT_COMPOSE_SMS:
			intent_intentConstructor = new Intent(Intent.ACTION_VIEW).setType(API.SMS_MIME_TYPE)
				.setComponent(new ComponentName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity"));
			break;
		case INTENT_VIEWCONVERSATIONS_SMS:
			intent_intentConstructor = new Intent(Intent.ACTION_VIEW).setType(API.SMS_MIME_TYPE)
				.setComponent(new ComponentName("com.android.mms", "com.android.mms.ui.ConversationList")); 
			break;
		case INTENT_ACTION_CONTACT_PHOTO_CLICK:
			intent_intentConstructor = new Intent(ctx, AppWidget4x4.class)
				.setAction(ACTION_CONTACT_PHOTO_CLICK)
				.setData(Uri.parse(uri_ViewWidget)).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			break;
		case INTENT_ACTION_CONTACT_NAME_CLICK:
			intent_intentConstructor = new Intent(ctx, AppWidget4x4.class)
				.setAction(ACTION_SMS_MESSAGE_BODY_TEXT_CLICK)
				.setData(Uri.parse(uri_ViewWidget)).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			break;
		case INTENT_ACTION_SMS_MESSAGE_BODY_TEXT_CLICK:
			intent_intentConstructor = new Intent(ctx, AppWidget4x4.class)
				.setAction(ACTION_SMS_MESSAGE_BODY_TEXT_CLICK)
				.setData(Uri.parse(uri_ViewWidget)).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			break;
		}return PendingIntent.getActivity(ctx,0,intent_intentConstructor,PendingIntent.FLAG_UPDATE_CURRENT);
	}

}
